/**
 * @author yinghui.zhang  组织机构管理
 */
 
Ext.ns("cn.christ.web.action.dict");
var orgView =cn.christ.web.action.dict.OrgView;

orgView = function() {
	var orgTree, store, grid, formPanel, win, grantorgTree, grantformPanel, grantwin;
	var fields =["id","name","code",'leader','duty','phone','partyAddress','partyTime',"remark","sort"];
	var sm = new Ext.grid.CheckboxSelectionModel({
		header:' ',singleSelect : true
	});
	return {
		init : function() {
			
			//------------------------------------------------- OrgTreePanel
			orgTree = this.createOrgTree();
			orgTree.on('click', function(node) {
				store.load( {
					params : {
						"page.start" : 0,
//						"page.limit"  : Ext.getCmp('page').pageSize,
						"page.limit"  : 200,
						"id" : node.attributes.id
					}
				});
			});
            orgTree.root.select();
            
            //------------------------------------------------- store
            store = this.createStore();
            //查询条件
			store.on('beforeload', function() {
					var selectModel = orgTree.getSelectionModel();
					var selectNode = selectModel.getSelectedNode();
					var id = 0,name;
					var leaf = false;
					if(selectNode){
					   var id = selectNode.attributes.id;
					   if(selectNode.isLeaf()){
						   leaf = true;
					   }
					} 
					if(queryRole){
						name=Ext.getCmp('pname').getValue();
					}else{
						name=undefined;
					}
					this.baseParams = {
						"page.colModel" : "id,name,code,remark,sort",
						"name" : name,
						"id" : id,
						"leaf" : leaf
					};
			});
            
			//------------------------------------------------- grid
			grid = this.createGrid();
			this.setGridGrog(); //设置可拖动
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					orgView.editInit();
				});
			}
			 
			// ------------------------------------------------- viewport
			new Ext.Viewport( {
				layout : 'border',
				items : [ {
					title : '组织机构',
					iconCls : 'layout_contentIcon',
					collapsible : true,
					width : 210,
					minSize : 160,
					maxSize : 280,
					split : true,
					region : 'west',
					autoScroll : true,
					items : [ orgTree ]
				}, {
					region : 'center',
					layout : 'fit',
					items : [ grid ]
				} ]
			});
			
			this.queryResItem();
		},
		
		createStore : function() {
			return new FrameWorkStore({
			     url : '/org/list.action',
			     fields : fields
		    });
		},
		
		createGrid : function() {
			return new ExtGrid(
					   {
						   	sm : sm,
							columnLines:true,//表格的竖线
							region : 'center',
							store : store,
							//拖动排序需要配置 enableDragDrop 属性 和 dropConfig属性  
					        enableDragDrop: true,  
					        dropConfig: {  
					            appendOnly:true  
					        },  
					        ddGroup: "GridDD", 
					        ddText : "拖动后，点击操作栏，保存排序按钮！",
					        renderTo: Ext.getBody(),
							columns : [new Ext.grid.RowNumberer(),sm,
								    { 
										sortable : true,
										autoWidth : true, 
										dataIndex : "name",
										header : "组织名称",
										width:60
									},{
										sortable : true,
										autoWidth : true,
										dataIndex : "code",
										header : "组织编码",
										width : 50
									},
									{
										sortable : true,
										autoWidth : true,
										dataIndex : "leader",
										header : "负责人",
										width : 50
									},
									{
										sortable : true,
										autoWidth : true,
										dataIndex : "duty",
										header : "职务",
										width : 50
									},
									{
										sortable : true,
										autoWidth : true,
										dataIndex : "phone",
										header : "联系电话",
										width : 50
									},{
										sortable : true,
										autoWidth : true,
										dataIndex : "partyTime",
										header : "聚会时间",
										width : 50
									},{
										sortable : true,
										autoWidth : true,
										dataIndex : "partyAddress",
										header : "聚会地址",
										width : 80
									},
									{
								    	sorttable:true,
								    	autowidth:true,
								    	dataIndex:'sort',
								    	header:'序号',
								    	width:45
								    },{
										xtype:'uxactioncolumn',
										header:'排序',
										autoWidth:false,
										width:30,				
										items: [{
											iconCls:'btn-up',
											tooltip:'向上（这里设定顺序后，请点击保存排序，使之生效）',
											stopSelection:false,
											scope:this,
											handler:function(g, r, c){
												orgView.onRowAction('btn-up',r);
											}
								        },{
											iconCls:'btn-last',
											tooltip:'向下（这里设定顺序后，请点击保存排序，使之生效）',
											stopSelection:false,
											scope:this,
											handler:function(g, r, c){
												orgView.onRowAction('btn-last',r);
											}
								        }]
									}
								],
							tbar : orgView.createTbar()
//							,
//							bbar : {
//								id : 'page',
//								xtype : 'pageinfobar',
//								pageSize : 20,
//								store : store,
//								pageMethod : orgView.queryResItem
//							}
				   });
		},
		
		setGridGrog : function() {
			  new Ext.dd.DropTarget(grid.container, {  
				        ddGroup : 'GridDD',  
				        copy    : false,  
				        notifyDrop : function(dd, e, data) {  
				            var rows = data.selections;  
				            var index = dd.getDragData(e).rowIndex;  
				            if (typeof(index) == "undefined") {  
				                return;  
				            }  
				            //确定正序还是倒序  
				            var mark = true;  
				            gridIndex = store.indexOf(rows[0]);  
				            if(index<gridIndex) mark = false;  
				              
				            for(i = 0; i < rows.length; i++) {  
				             var rowData;  
				                if(mark){  
				                    rowData = rows[i];  
				                 }else{  
				                    rowData = rows[rows.length-i-1];  
				                }  
				                if(!this.copy)   
				                    store.remove(rowData);  
				                store.insert(index, rowData);  
				            }  
				            var sm = grid.getSelectionModel();  
				            sm.clearSelections();  
				            grid.getView().refresh();//刷新序号    
				                
				        }  
               });  
		},
		
		createTbar : function() {
			if(editRole){
				tbarOpr.push('-', {
					text : '保存排序',
					iconCls : 'save',
					handler : function() {
						var ids = '';
						var i =0;
						grid.getStore().each(function(r){
							++i;
						   ids +=r.id+",";
						});
						if(i==0){
						  Ext.Mytip.msg('提示','无记录排序');
						} else if(i==1){
						   Ext.Mytip.msg('提示','只有一条记录，无需排序');
						} else {
							var selectModel = orgTree.getSelectionModel();
							var selectNode = selectModel.getSelectedNode();
							var parentId = selectNode.attributes.id;
							Ext.Ajax.request({
								url : cfg.cxt+'/org/sort.action',
								success : function(response) {
									 var rt = Ext.decode(response.responseText);
									 if (rt.success){
									 	orgView.refreshNode(parentId); //刷新父节点
									    Ext.Mytip.msg('提示', '排序成功！');
									 } else {
										bangni.ajaxError(response);
									 }
								},
							    failure : bangni.ajaxError,
								params : {
									"ids" : ids
								}
							});
						
						}
					}
				},{
					xtype : "label",
				    text:'（可直接拖动列进行排序）'
				}
				);
			}
			
			
			if(queryRole){
				tbarOpr.push('->');
				tbarOpr.push( new Ext.form.TextField( {
					id : 'pname',
					emptyText : '请输入组织名称',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								orgView.queryResItem();
							}
						}
					},
					width : 130
				}));
				tbarOpr.push({
					text : '查询',
					iconCls : 'previewIcon',
					handler : function() {
						orgView.queryResItem();
					}
				}, '-', {
					text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						window.location.reload();
					}
				});
						
				tbarOpr.push('-'); 
				}
				return tbarOpr;
		},
		
		createOrgTree : function() {
			return new Ext.tree.TreePanel( {
						loader : new Ext.tree.TreeLoader( {
							dataUrl :  cfg.cxt+'/org/tree.action',
							  listeners:{
				                beforeload:function(treeLoader, node){
				                    this.baseParams={  
				                        nodeId:node.attributes.id
				                    };
				                },
				                loadexception : bangni.storeLoadError
				            }
						}),
						root : new Ext.tree.AsyncTreeNode( {  
							text : '组织管理',
							expanded : true,
							id : '0'
						}),
						title : '',
						applyTo : 'orgTreeDiv',
						autoScroll : false,
						animate : false,
						useArrows : false, 
						border : false
					});
		},
		
		queryResItem : function(v) {
//			if(!v) v = Ext.getCmp('page').pageSize;
		    store.load( {
				params : {
					"page.start" : 0,
					"page.limit" : 200
				}
			});
		},
		
		onRowAction : function(c,i) {
			var g = grid.getStore();
			switch (c) {
			case "btn-up":
				if (i == 0) {
					Ext.Mytip.msg("操作信息", "已经为第一条!");
					return;
				}
				var h = g.getAt(i - 1);
				var f = g.getAt(i);
				g.removeAt(i);
				g.removeAt(i - 1);
				g.insert(i - 1, f);
				g.insert(i, h);
				break;
			case "btn-last":
				if (i == g.getCount() - 1) {
					Ext.Mytip.msg("操作信息", "已经为最后一条!");
					return;
				}
				var h = g.getAt(i);
				var f = g.getAt(i + 1);
				g.removeAt(i + 1);
				g.removeAt(i);
				g.insert(i, f);
				g.insert(i + 1, h);
				break;
			default:
				break;
			}
		},
		
		clearForm : function(pForm) {
			var formItems = pForm.items['items'];
		    for (i = 0; i < formItems.length; i++) {
		        element = formItems[i];
		        element.setValue('');
		        element.reset(); // 避免出现红色波浪线
		    };
		},
		
		addInit : function() {
			this.onAddOrEditInit('common');
			var flag = Ext.getCmp('windowmode').getValue();
			if (typeof (flag) != 'undefined') {
				formPanel.form.getEl().dom.reset();
			} else {
				this.clearForm(formPanel.getForm());
			}
			
			var selectModel = orgTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			Ext.getCmp('parentresname').setValue(selectNode.attributes.text);
			Ext.getCmp('fatherId').setValue(selectNode.attributes.id);
			Ext.getCmp('sort').setValue(1);
			win.setTitle('<center>新增组织(机构)信息</center>');
			Ext.getCmp('windowmode').setValue('add');
			win.show();
			Ext.getCmp("code").getEl().dom.readOnly = false; 
		},
		
		editInit : function() {
			this.onAddOrEditInit('common');
			var record = grid.getSelectionModel().getSelected();
			if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择您要修改的记录');
				return;
			}
			formPanel.getForm().loadRecord(record);
			win.setTitle('<center>修改组织(机构)信息</center>');
			Ext.getCmp('windowmode').setValue('edit');
			var selectModel = orgTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			Ext.getCmp('fatherId').setValue(selectNode.attributes.id);
			if(selectNode.isLeaf()){
				Ext.getCmp('parentresname').setValue(selectNode.parentNode.attributes.text);
			} else {
				Ext.getCmp('parentresname').setValue(selectNode.attributes.text);
			}
			win.show();
			Ext.getCmp("code").getEl().dom.readOnly = true; 
		},
		
		onAddOrEditInit : function(type){
			switch(type) {
				case 'common' : {
				     if(!formPanel){
						 formPanel = orgForm.createFormPanel();
					 } 
					 if(!win){
					 	 win = orgForm.createWindow();
					 }
				 } break;
				 
				 case 'grant' : {
				 	 if(!grantorgTree){
				 	 	 grantorgTree = orgForm.createGrantModuleTree();
				 	     orgForm.setGrantModuleTreeClick();
				 	 }
				 	 if(!grantformPanel){
				 	 	grantformPanel =  orgForm.createGrantFormPanel();
				 	 }
				 	 if(!grantwin){
				 	 	grantwin = orgForm.createGrantWin();
				 	 	orgForm.setGrantWinOnShow();
				 	 }
				 } break;
				 
				 default : {
				 	 Ext.Mytip.msg('提示', '初始化操作类型['+type+']不存在！');
				 }
			}
			
		},
		
		subForm : function(url) {
			var mode = Ext.getCmp('windowmode').getValue();
			var selectModel = orgTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			var fatherId =selectNode.attributes.id;
			formPanel.form.submit({
				url : cfg.cxt+url,
				waitTitle : '提示',
				method : 'POST',
				waitMsg : '正在处理数据,请稍候...',
				success : function(form, action) {
					var r = action.result.status;
					if (r == 200){
						win.hide();
						orgView.refreshNode(fatherId); //刷新父节点
						form.reset();
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增成功！');
						else
						    Ext.Mytip.msg('提示', '修改成功！');
					}else if(r==201){//新增时存在相同的记录
						 Ext.Mytip.msg('提示', action.result.info);
					} else{
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增失败！');
						else
						    Ext.Mytip.msg('提示', '修改失败！');
					}
				},
				failure : bangni.sumbitError
			});
		},
		
		deleteItem : function() {
			var record = grid.getSelectionModel().getSelected();
	        if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择要删除的记录！');
				return;
			}
	        var selectModel = orgTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			var fatherId = selectNode.attributes.id;
			Ext.Msg
			   .confirm(
					'请确认',
					'<span style="color:red"><b>提示：</b>你真的要删除选中单位(机构)吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt+'/org/del.action',
								success : function(response) {
									 var r = Ext.decode(response.responseText);
									 if (r.success) {
									 	if(r.status == 200){
									 		 orgView.refreshNode(fatherId); // 刷新父节点
											 Ext.Mytip.msg('提示','删除成功！');
										 } else {
											 Ext.Mytip.msg('提示',r.info);
										 }
									} else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"id" : record.id
								}
							});
						}
				});
		},
		
		grant : function(name) {
			 this.onAddOrEditInit('grant');
			 grantwin.setTitle('机构[ '+name+' ]授权');
			 grantwin.show();
		},
		
		editOnePermission : function(e,y){
			    var node  = grantorgTree.getSelectionModel().getSelectedNode();
				var record = grid.getSelectionModel().getSelected();
			    var param = 'principalType=Org&principalId='+record.id+'&moduleId='+node.attributes.id+'&permissionExt='+e+'&yes='+y;
		     	ajaxSyncCall( cfg.cxt+'/acl_addOrUpdatePermission.do',param);
		},
		
		editPermission : function (param,url) {
			var record = grid.getSelectionModel().getSelected();
			param = String.format(param, record.id)
	     	return ajaxSyncCall( url , param);
		},
		
		getExpandedNodeIds : function(startNode){
			var expandedNodeIds=[];
	        startNode = startNode || orgTree.root;
	        var f = function(){
	            if(this.expanded){
	            	expandedNodeIds.push(this.attributes.id);
	            }
	        };
	        startNode.cascade(f);
	        return expandedNodeIds;
		},
		
		refreshNode : function(nodeid) {
			var expandedNodeIds=[];
			var reExpanded=function() {
				this.eachChild(function() {
					for(var i=0;i<expandedNodeIds.length;i++) {
						if(this.attributes.id==expandedNodeIds[i]) {
							if(!this.attributes.leaf)
								this.reload(reExpanded);
							break;
						}
					}
				})
			}
			
			//获取所有展开的节点id
			var node = orgTree.getNodeById(nodeid);
			/* 异步加载树在没有展开节点之前是获取不到对应节点对象的 */
			if (Ext.isEmpty(node)||Ext.isEmpty(node.parentNode)) {
				expandedNodeIds=this.getExpandedNodeIds(orgTree.root);
				orgTree.root.reload(reExpanded);
				orgTree.root.select();
				orgTree.fireEvent("click",orgTree.root);
			} else if (!Ext.isEmpty(node.parentNode)) {
				var p=node.parentNode;
				expandedNodeIds=this.getExpandedNodeIds(p);
				var expanded=node.expanded ;
				p.reload(function() {
					var newNode=orgTree.getNodeById(nodeid);
					if(newNode!=null) {
						newNode.select();
						orgTree.fireEvent("click",newNode);
					} else {
						p.select();
						orgTree.fireEvent("click",p);
					}
					reExpanded.call(this);
				});
			} 	
		 }
	}
}();
Ext.onReady(orgView.init, orgView);